package Code.Objects.Characters.Player.Weapons.Ranged.AmmoBased;

import org.jrabbit.base.input.KeyboardHandler;
import org.jrabbit.standard.game.graphics.skins.animation.AnimatedSkin;
import org.lwjgl.input.Keyboard;

import Code.Objects.Characters.Player.Player;
import Code.Objects.Characters.Player.Weapons.PlayerWeapon;

public class PlayerAmmoBasedWeapon extends PlayerWeapon
{
	protected int ammoInClip;
	protected int ammoPerClip;
	protected int spareAmmo;
	protected int maxClips;
	protected boolean reloading;
	protected int reloadDuration;
	protected int reloadTimer;
	protected int reloadAmmo;
	
	public PlayerAmmoBasedWeapon(AnimatedSkin skin, Player p)
	{
		super(skin, p);
		ammoPerClip = 20;
		maxClips = 5;
		fillAmmo();
		reloading = false;
		reloadDuration = 20000;
		reloadAmmo = 0;
	}

	public void beginReload()
	{
		reloadAmmo = ammoPerClip - ammoInClip;
		if(spareAmmo < reloadAmmo)
		{
			reloadAmmo = spareAmmo;
		}
		spareAmmo -= reloadAmmo;
		reloadTimer = 0;
		reloading = true;
	}
	
	public void finishReload()
	{
		ammoInClip += reloadAmmo;
		reloading = false;
	}
	
	public void reload(double duration)
	{
		reloadTimer += duration;
		if(reloadTimer >= reloadDuration)
		{
			reloadTimer -= reloadDuration;
			finishReload();
		}
	}
	
	public void fillAmmo()
	{
		ammoInClip = ammoPerClip;
		spareAmmo = maxClips * ammoInClip;
	}
	
	public void addClips(int numClips)
	{
		spareAmmo += numClips * ammoInClip;
		if(spareAmmo > maxClips * ammoInClip)
		{
			spareAmmo = maxClips * ammoInClip;
		}
		
	}
	
	public void outOfAmmo()
	{
		
	}
	
	public void updateWeapon(int delta)
	{
		if(KeyboardHandler.wasKeyPressed(Keyboard.KEY_R))
		{
			if(!reloading && ammoInClip != ammoPerClip)
			{
				beginReload();
			}
		}
		adjust();
		if(reloading)
		{
			reload(delta);
		}
		else
		{
			activeUpdate(delta);
		}
	}
	
	public void activeUpdate(int delta)
	{
		
	}
	
	public void attemptToFire()
	{
		if(ammoInClip > 0)
		{
			fire();
			ammoInClip--;
			if(ammoInClip == 0)
			{
				if(spareAmmo > 0)
				{
					beginReload();
				}
				else
				{
					outOfAmmo();
				}
			}
		}
		else
		{
			if(spareAmmo > 0)
			{
				beginReload();
			}
			else
			{
				outOfAmmo();
			}
		}
	}
}
